//data/models/Student.kt（完整版）

package com.example.xxcjgl.data.models

import com.google.gson.annotations.SerializedName
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 学生成绩信息模型
 */
data class Student(
    @SerializedName("xscjb_xh")
    val studentId: Int,

    @SerializedName("xscjb_mc")
    val studentName: String,

    @SerializedName("xscjb_xb")
    val gender: String, // "0"-女, "1"-男

    @SerializedName("xscjb_sxcj")
    val mathScore: Float?,

    @SerializedName("xscjb_ywcj")
    val chineseScore: Float?,

    @SerializedName("xscjb_csrrq")
    val examDate: String?, // yyyy-MM-dd格式

    @SerializedName("xscjb_jmbz")
    val encryptionFlag: Int, // 0-未加密, 1-已加密

    @SerializedName("xdcjb_jmmy")
    val encryptionKey: String? = null,

    @SerializedName("created_at")
    val createdAt: String? = null,

    @SerializedName("updated_at")
    val updatedAt: String? = null
) {
    /**
     * 性别显示文本
     */
    val genderText: String
        get() = if (gender == "1") "男" else "女"

    /**
     * 是否已加密
     */
    val isEncrypted: Boolean
        get() = encryptionFlag == 1

    /**
     * 格式化考试日期
     */
    val formattedExamDate: String
        get() {
            return if (!examDate.isNullOrBlank()) {
                try {
                    val inputFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                    val outputFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault())
                    val date = inputFormat.parse(examDate)
                    outputFormat.format(date ?: Date())
                } catch (e: Exception) {
                    examDate ?: "未知日期"
                }
            } else {
                "暂无成绩"
            }
        }

    /**
     * 数学成绩显示（考虑加密状态）
     */
    fun getMathScoreDisplay(decryptionKey: String? = null): String {
        return if (isEncrypted) {
            if (decryptionKey == encryptionKey) {
                mathScore?.toString() ?: "无"
            } else {
                "****"
            }
        } else {
            mathScore?.toString() ?: "无"
        }
    }

    /**
     * 语文成绩显示（考虑加密状态）
     */
    fun getChineseScoreDisplay(decryptionKey: String? = null): String {
        return if (isEncrypted) {
            if (decryptionKey == encryptionKey) {
                chineseScore?.toString() ?: "无"
            } else {
                "****"
            }
        } else {
            chineseScore?.toString() ?: "无"
        }
    }

    /**
     * 获取总成绩
     */
    fun getTotalScore(decryptionKey: String? = null): Float? {
        return if (isEncrypted && decryptionKey != encryptionKey) {
            null
        } else {
            val math = mathScore ?: 0f
            val chinese = chineseScore ?: 0f
            if (math > 0 && chinese > 0) math + chinese else null
        }
    }

    /**
     * 获取平均成绩
     */
    fun getAverageScore(decryptionKey: String? = null): Float? {
        val total = getTotalScore(decryptionKey)
        return total?.div(2)
    }

    /**
     * 验证学生数据的有效性
     */
    fun isValid(): Boolean {
        return studentName.isNotBlank() &&
                studentName.length in 2..20 &&
                gender in listOf("0", "1") &&
                (mathScore == null || mathScore in 0f..150f) &&
                (chineseScore == null || chineseScore in 0f..150f)
    }

    companion object {
        /**
         * 创建新的学生实例（用于添加操作）
         */
        fun createNew(
            name: String,
            gender: String,
            mathScore: Float? = null,
            chineseScore: Float? = null,
            encrypt: Boolean = false,
            encryptionKey: String? = null
        ): Student {
            val currentDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
            return Student(
                studentId = 0, // 0表示新记录
                studentName = name,
                gender = gender,
                mathScore = mathScore,
                chineseScore = chineseScore,
                examDate = currentDate,
                encryptionFlag = if (encrypt) 1 else 0,
                encryptionKey = if (encrypt) encryptionKey else null
            )
        }
    }
}

/**
 * 学生统计信息
 */
data class StudentStats(
    val totalCount: Int,
    val maleCount: Int,
    val femaleCount: Int,
    val encryptedCount: Int,
    val avgMathScore: Float,
    val avgChineseScore: Float,
    val maxMathScore: Float,
    val maxChineseScore: Float
)

/**
 * 学生成绩趋势
 */
data class ScoreTrend(
    val date: String,
    val avgMath: Float,
    val avgChinese: Float,
    val studentCount: Int
)
